#include <SDL/SDL.h>

typedef int bool;

bool flip(unsigned char * src, int width, int height, int num);
SDL_Surface *pscreen;
SDL_Overlay *poverlay;
int main(int argc, char **argv) {
    if (argc != 4) {
        return 1;
    }
    int readsize;
    int width, height;
    width = atoi(argv[2]);
    height = atoi(argv[3]);
    readsize = width * height * 3 / 2;
    unsigned char *yuvframe = malloc(readsize);

    atexit(SDL_Quit);

    if (SDL_Init(SDL_INIT_VIDEO) < 0) {
        exit(1);
    }
    pscreen = SDL_SetVideoMode(width, height, 24, SDL_SWSURFACE);
    if (pscreen == NULL) {
    }
    poverlay = SDL_CreateYUVOverlay(width, height, SDL_YV12_OVERLAY, pscreen);
    if (poverlay == NULL) {
    }


    FILE *fyuv;
    fyuv = fopen(argv[1], "rb");
    if (fyuv == NULL) {
        return -1;
    }
    while (1) {
        int rsize = fread(yuvframe, sizeof(char), readsize, fyuv);
        if (rsize > 0) {
            static int num = 0;
            num++;
            flip(yuvframe, width, height, num);
        }
        //SDL_Delay(400);

        //SDL Event handler
        SDL_Event sdl_event;
        while (SDL_PollEvent(&sdl_event)) {
            switch (sdl_event.type) {
            case SDL_KEYDOWN:
                break;
            case SDL_KEYUP:
                if (sdl_event.key.keysym.sym == SDLK_q) {
                    return 0;
                }
                break;
            case SDL_QUIT:
                printf("OnQuit\n");
                return 0;
            default:
                break;
            }
        }
    }
    return 0;
}

bool flip(unsigned char * src, int width, int height, int num) {
    unsigned char *outy, *outu, *outv, *op[3];
    int y;
    SDL_Rect rect;
    rect.w = width;
    rect.h = height;
    rect.x = 0;
    rect.y = 0;
    SDL_LockSurface(pscreen);
    SDL_LockYUVOverlay(poverlay);
    outy = src;
    outu = src + width * height * 5 / 4;
    outv = src + width * height;

    for (y = 0; y < pscreen->h && y < poverlay->h; y++) {
        op[0] = poverlay->pixels[0] + poverlay->pitches[0] * y;
        op[1] = poverlay->pixels[1] + poverlay->pitches[1] * (y / 2);
        op[2] = poverlay->pixels[2] + poverlay->pitches[2] * (y / 2);
        memcpy(op[0], outy + y * width, width);
        if (y % 2 == 0) {
            memcpy(op[1], outu + width / 2 * y / 2, width / 2);
            memcpy(op[2], outv + width / 2 * y / 2, width / 2);
        }
    }
    SDL_UnlockYUVOverlay(poverlay);
    SDL_UnlockSurface(pscreen);
    SDL_DisplayYUVOverlay(poverlay, &rect);

    char pnum[10];
    sprintf(pnum, "#%d", num);
    SDL_WM_SetCaption(pnum, NULL);

    return 0;
}
